package cn.huijielong.modules.oss.entity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.springframework.web.multipart.MultipartFile;

import cn.huijielong.common.exception.VSException;
import cn.huijielong.common.utils.Base64Upload;


public class Base64File implements MultipartFile {
	private Object source;
	private File dest;
	private byte[] content;
	private long size;
	@Override
	public String getName() {
		return null;
	}
	public static Base64File create(String base64,Object source) {
		try {
			String prefix=UUID.randomUUID().toString().replaceAll("-", "");
			int index=base64.indexOf("|");
			String suffix=base64.substring(0, index);
			base64=base64.substring(index+1);
			
			File tmp=File.createTempFile("vs-", "."+suffix);
			Base64Upload.uploadMutilImage(base64, tmp);
			Base64File bfile=new Base64File();
			bfile.transferTo(tmp);
			bfile.setSource(source);
			return bfile;
		}catch(Exception e) {
			throw new VSException(e);
		}
		
	}
	@Override
	public String getOriginalFilename() {
		return dest.getName();
	}

	@Override
	public String getContentType() {
		String name=dest.getName();
		return name.substring(name.lastIndexOf(".")+1);
	}

	@Override
	public boolean isEmpty() {
		return size>0;
	}

	@Override
	public long getSize() {
		return size;
	}

	@Override
	public byte[] getBytes() throws IOException {
		return content;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return null;
	}
	
	public Object getSource() {
		return source;
	}
	public void setSource(Object source) {
		this.source = source;
	}
	@Override
	public void transferTo(File dest) throws IOException, IllegalStateException {
		this.dest=dest;
		this.content=org.apache.commons.io.FileUtils.readFileToByteArray(dest);
		this.size=dest.getTotalSpace();
	}

}
